<template>
    <div class="user-selector">
        <!-- 用户列表展示区域，按角色分组 -->
        <div class="selected-user-list">
            <el-collapse accordion>
                <el-collapse-item v-for="role in roles" :key="role.roleId" :title="role.roleName">
                    <div class="user-tags">
                        <el-tag v-for="user in role.users" :key="user.userId" closable @close="removeUser(user,role)"
                            class="user-tag" type="primary">
                            <el-avatar :src="user.avatar" size="small" />
                            <span>{{ user.nickname }}</span>
                        </el-tag>
                    </div>
                </el-collapse-item>
            </el-collapse>
        </div>

        <!-- 用户选择器 -->
        <el-select v-model="selectedUserId" placeholder="邀请用户" style="width: 300px; margin-top: 16px;"
            @change="handleUserSelect" filterable remote @remote-method="filterUsers" :loading="loading"
            :multiple="multiple" clearable>
            <el-option v-for="user in filteredUsers" :key="user.userId" :label="user.nickname" :value="user.userId!">
                <template #default="{}">
                    <div class="option-content">
                        <el-avatar :src="user.avatar" size="small" />
                        <span style=" margin-left: 5px;">{{ user.nickname }}</span>
                        <span class="user-id" style=" margin-left: 20px;">ID: {{ user.userId }}</span>
                    </div>
                </template>
            </el-option>
        </el-select>

        <!-- 错误提示 -->
        <el-alert v-if="error" title="Error fetching users" type="error" show-icon></el-alert>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, nextTick } from 'vue'
import {
    ElCollapse,
    ElCollapseItem,
    ElTag,
    ElAvatar,
    ElSelect,
    ElOption,
    ElAlert
} from 'element-plus'
import type { User } from '../../type/User'
import type { Role } from '../../type/Role'

// 接收 props
const props = defineProps({
    roles: {
        type: Array as () => Role[],
        required: true
    },
    availableUsers: {
        type: Array as () => User[],
        required: true
    },
    selectedUsers: {
        type: Array as () => User[],
        required: true
    },
    multiple: {
        type: Boolean,
        default: true
    }
})

// 定义 emits
const emit = defineEmits<{
    (e: 'update:selectedUsers', users: User[]): void;
    (e: 'remove-user', payload: { user: User, role: Role }): void;
}>()

// 内部状态
const selectedUsersInternal = ref<User[]>([...props.selectedUsers])
const selectedUserId = ref<string | string[]>('')
const searchQuery = ref<string>('')

// 加载状态和错误信息
const loading = ref<boolean>(false)
const error = ref<string | null>(null)

// 扁平化可用用户列表，便于搜索和选择
const usersFlat = computed(() => {
    return props.availableUsers
})

// 过滤用户列表，根据搜索查询
const filteredUsers = computed(() => {
    if (!searchQuery.value) {
        return usersFlat.value
    }
    const lowerQuery = searchQuery.value.toLowerCase()
    return usersFlat.value.filter(user =>
        user.nickname?.toLowerCase().includes(lowerQuery) ||
        user.userId?.includes(searchQuery.value)
    )
})

// 搜索方法
function filterUsers(query: string) {
    searchQuery.value = query
}

// 处理用户选择
function handleUserSelect(userId: string | string[]) {
    if (props.multiple) {
        const selectedIds = Array.isArray(userId) ? userId : [userId]
        const newUsers = usersFlat.value.filter(
            u => selectedIds.includes(u.userId!) && !selectedUsersInternal.value.find(su => su.userId === u.userId)
        )
        selectedUsersInternal.value.push(...newUsers)
    } else {
        const user = usersFlat.value.find(u => u.userId === userId)
        if (user && !selectedUsersInternal.value.find(su => su.userId === user.userId)) {
            selectedUsersInternal.value = [user]
        }
    }
    emit('update:selectedUsers', selectedUsersInternal.value)
}


function removeUser(user: User,role:Role) {

 /* // 从 selectedUsersInternal 中移除
    selectedUsersInternal.value = selectedUsersInternal.value.filter(u => u.userId !== user.userId);

    // 从 roles 中移除该用户
    props.roles.forEach(role => {
        role.users = role.users?.filter(u => u.userId !== user.userId);
    });

    // 创建 roles 的副本，并从副本中移除用户
    //确保 props.roles 是不可变的。如果直接修改了 props.roles，会违反 Vue 的单向数据流原则，建议通过拷贝修改。
    const updatedRoles = props.roles.map(role => ({
        ...role,
        users: role.users?.filter(u => u.userId !== user.userId),
    })); */

    // 通知父组件更新
    emit('update:selectedUsers', selectedUsersInternal.value);
    emit('remove-user', { user, role });
}
// 监听外部 selectedUsers 的变化，保持同步
watch(
    () => props.selectedUsers,
    (newVal) => {

        nextTick(() => {
            // 强制刷新 不行有问题 TODO 子组件视图不更新
            selectedUsersInternal.value = [...newVal]
        });
    },
    {
        immediate: true,
        deep: true
    }

)
</script>

<style lang="scss" scoped>
.user-selector {
    .selected-user-list {
        margin-bottom: 12px;

        :deep(.el-collapse-item__header) {
            font-weight: bold;
            padding-left: 20px;
            /* 增加左边距 */
        }

        .user-tags {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 8px;

        }

        :deep(.user-tag) {
            display: flex;
            align-items: center;
            padding: 2px 8px;
            height: 32px;


            .el-avatar {
                margin-right: 4px;
            }
        }
    }

    .option-content {
        display: flex;
        align-items: center;
        width: 100%;
    }

    :deep(.option-content .user-id) {
        margin-left: 20px;
        color: var(--el-text-color-secondary);
        font-size: 13px;
    }

    :deep(.selected-user-info) {
        margin-top: 20px;
        display: flex;
        flex-direction: column;
        align-items: flex-start;

        img {
            margin-bottom: 10px;
        }
    }
}
</style>